<?php
/**
 * XuYuan Project
 *
 * @package	XueYuan 
 * @author	Jiuchi Team
 * @since	Version 1.0.0
 * @filesource
 */
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * User controller class
 * @author Wayne Yu
 */
class Topic extends CI_Controller {
	public function __construct(){
		parent::__construct();
		$this->load->library('session');
		$this->load->library('apioutput');
		$this->load->library('msgblock');
		$this->load->helper('url');
		$uid = $this->session->userdata('uid');
		if(empty($uid)){
			redirect(site_url('login'));
		}
		$this->load->model('user_model');
		$this->load->model('user_dynamic_model');
		$this->load->model('circle_model');
		$this->load->model('circle_category_model');
		$this->load->model('circle_user_model');
		$this->load->model('circle_admin_model');
		$this->load->model('topic_model');
		$this->load->model('comment_model');
	}
	
	/**
	 * Create page
	 */
	public function create($cid){
		$data = array(
				'cid'	=>	$cid
		);
		$this->load->view('topic/createTopic', $data);
	}
	
	/**
	 * create circle post
	 */
	public function createPost($cid){
		$input = $this->input->post();
		if(empty($input['title'])|| empty($input['content'])){
			die("<script>alert('非法请求，请联系管理员！');window.location.href='".site_url('topic/create/'.$cid)."';</script>");
		}
	
		
		$circleInfo = $this->circle_model->getInfo($cid);
		if(!$this->circle_user_model->checkIsMember($this->session->userdata('uid'), $cid)){
			die("<script>alert('您尚未加入该圈子，请先申请加入！');window.location.href='".site_url('topic/create/'.$cid)."';</script>");
		}
		$topic_img = $this->getPostImg($cid);
		$data = array(
				'circle_id'				=>	$cid,
				'circle_name'			=>	$circleInfo['id'],
				'user_id'				=>	$this->session->userdata('uid'),
				'title'					=>	$input['title'],
				'topic_img'				=>	$topic_img,
				'content'				=>	htmlspecialchars($input['content'],ENT_QUOTES),
		);

		//save
		$this->topic_model->begin();
		$tid = $this->topic_model->createEntity($data);
		if($tid <= 0){
			die("<script>alert('创建失败，请稍后重试！');window.location.href='".site_url('topic/create/'.$cid)."';</script>");
		}
		$data = array(
				'user_id'		=> $this->session->userdata('uid'),
				'title'			=> $input['title'],
				'obj_id'		=> $tid,
				'type'			=> 1,
				'content'		=> $input['content'],
				'content_img'	=> $topic_img,
				'circle_id'		=> $cid,
				'circle_name'	=> $circleInfo['name'],
		);
		$this->user_dynamic_model->createEntity($data);
		if($tid <= 0){
			$this->topic_model->rollback();
			die("<script>alert('创建失败，请稍后重试！');window.location.href='".site_url('topic/create/'.$cid)."';</script>");
		}
		
		$res = $this->circle_model->updateInfo($cid,array('topic_number' => ($circleInfo['topic_number']+1)));
		if($res <= 0){
			$this->topic_model->rollback();
			die("<script>alert('创建失败，请稍后重试！');window.location.href='".site_url('topic/create/'.$cid)."';</script>");
		}
		$this->topic_model->commit();
		
		die("<script>alert('话题发表成功！');window.parent.$.fancybox.close();</script>");
	}
	
	private function getPostImg($cid){
		if(empty($_FILES['filename'])){
			return '';
		}
		$nameExten = explode('.', $_FILES['filename']['name']);
		$type = end($nameExten);
		if(!in_array($_FILES['filename']['type'], array('image/bmp', 'image/gif', 'image/jpeg', 'image/jpg', 'image/png'))){
			$this->msgblock->addError('图片格式不正确！');
			return '';
		}
		if($_FILES['filename']['size'] > 5*1024*1024){
			$this->msgblock->addError('图片过大!');
			return '';
		}
			
		$path = dirname(BASEPATH).'/uploads/topic/'.$cid;
		if(!is_dir($path)){
			if(false == mkdir($path)){
				$this->msgblock->addError('没有权限，请联系管理员！');
				return '';
			}
		}
		$filepath= $path.'/'.$_FILES['filename']['name'];
			
		if(is_uploaded_file($_FILES['filename']['tmp_name'])){
			if(move_uploaded_file($_FILES['filename']['tmp_name'], $filepath)){
				return '/uploads/topic/'.$cid.'/'.$_FILES['filename']['name'];
			} else{
				$this->msgblock->addError('没有权限，请联系管理员！');
				return '';
			}
		} else{
			$this->msgblock->addError('没有权限，请联系管理员！');
			return '';
		}
	}
	
	public function view($topic_id){
		$topicInfo = $this->topic_model->getInfo($topic_id);
		$userInfo = $this->user_model->getInfo($topicInfo['user_id']);
		$data = array(
				'topicInfo'	=>	$topicInfo,
				'userInfo'	=>	$userInfo
		);
		$this->load->view('topic/view', $data);
	}
	
	/**
	 * get topics' comments
	 */
	public function getTopicComments($tid){
		$input = $this->input->post();
		$pageSize = isset($input['amount'])?$input['amount']:5;
		$laseItem = isset($input['last'])?$input['last']:0;
		
		$data = $this->comment_model->getTopicComments($tid, $pageSize, $laseItem);
		foreach ($data as $key => $val){
			$uInfo  = $this->user_model->getInfo($val['user_id']);
			$data[$key] = array(
					'headportrait'	=>	'<a href="'.site_url('user/view/'.$val['user_id']).'"><img style="width:40px;" src="'.(isset($uInfo['headportrait'])?$uInfo['headportrait']:'').'" class="img-avatar"></a>',
					'name'			=>	isset($uInfo['nickname'])?'<a href="'.site_url('user/view/'.$val['user_id']).'">'.$uInfo['nickname'].'</a>':'',
					'comment_photo'	=>	($val['comments_img'])?'<img src="'.$val['comments_img'].'" href="'.$val['comments_img'].'" class="rep-img">':'',
					'content'		=>	$val['content'],
					'viewbutton'	=>	'<a href="'.site_url('comment/view/'.$val['id']).'">查看回复</a>'
			);
		}
		echo json_encode($data);
	}
	
	/**
	 * Create page
	 */
	public function search(){
		$data = array(
				'keyword'	=>	$this->input->get('keyword'),
		);
		$this->load->view('topic/searchResults', $data);
	}
	
	/**
	 * search topics
	 */
	public function searchTopics(){
		$input = $this->input->post();
		$pageSize = isset($input['amount'])?$input['amount']:5;
		$laseItem = isset($input['last'])?$input['last']:0;
		$keyword  = $this->input->get('keyword');
	
		$data = $this->topic_model->searchTopics($keyword, $pageSize, $laseItem);
		foreach ($data as $key => $val){
			$uInfo  = $this->user_model->getInfo($val['user_id']);
			$data[$key] = array(
					'headportrait'	=>	'<a href="'.site_url('user/view/'.$val['user_id']).'"><img style="width:40px;" src="'.(isset($uInfo['headportrait'])?$uInfo['headportrait']:'').'" class="img-avatar"></a>',
					'name'			=>	isset($uInfo['nickname'])?'<a href="'.site_url('user/view/'.$val['user_id']).'">'.$uInfo['nickname'].'</a>':'',
					'title'			=>	'<a href="'.site_url('topic/view/'.$val['id']).'">'.$val['title'].'</a>',
					'topicphoto'	=>	($val['topic_img'])?'<img src="'.$val['topic_img'].'" href="'.$val['topic_img'].'" class="rep-img">':'',
					'content'		=>	htmlspecialchars_decode($val['content'])
			);
		}
		echo json_encode($data);
	}
	
	public function userAction(){
		$input = $this->input->post();
		if(empty($input['action'])|| empty($input['circle_id'])){
			$this->apioutput->apiResponseError('非法请求，请联系管理员！');
		}
		$cid = $input['circle_id'];
		$uid = $this->session->userdata('uid');
		$circleInfo = $this->circle_model->getInfo($cid);
		if(!$circleInfo){
			$this->apioutput->apiResponseError('您申请加入的圈子不存在！');
		}
	
		switch ($input['action']){
			case 'concern':
				if($this->circle_user_model->checkIsConcerned($uid, $cid) == TRUE){
					$this->apioutput->apiResponseError('您已经关注过该圈，请勿重复提交申请！');
				}
	
				$data = array(
						'circle_id'	=>	$cid,
						'user_id'	=>	$uid
				);
				$res = $this->circle_user_model->createEntity($data);
				if($res <= 0){
					$this->apioutput->apiResponseError('关注失败，请稍后重试！');
				}
	
				$this->apioutput->apiResponseSuccess();
				break;
			case 'unconcern':
				if(!$this->circle_user_model->checkIsConcerned($uid, $cid) == TRUE){
					$this->apioutput->apiResponseError('您尚未关注该圈！');
				}
	
				$this->circle_user_model->begin();
	
				if($this->circle_user_model->checkIsMember($uid, $cid) == TRUE){
					if($circleInfo['user_number']-1 >= 0){
						$uno = $circleInfo['user_number']-1;
					}else{
						$uno = 0;
					}
					$res = $this->circle_model->updateInfo($cid,array('user_number' => $uno));
					if($res <= 0){
						$this->circle_user_model->rollback();
						$this->apioutput->apiResponseError('关注失败，请稍后重试！');
					}
				}
				$res = $this->circle_user_model->unconcern($uid, $cid);
				if(!$res){
					$this->circle_user_model->rollback();
					$this->apioutput->apiResponseError('取消关注失败，请稍后重试！');
				}
				$res = $this->circle_applicant_model->cleardata($uid, $cid);
				if(!$res){
					$this->circle_user_model->rollback();
					$this->apioutput->apiResponseError('取消关注失败，请稍后重试！');
				}
	
				$this->circle_user_model->commit();
	
				$this->apioutput->apiResponseSuccess();
				break;
				$this->apioutput->apiResponseSuccess();
				break;
			case 'join':
				if($this->circle_user_model->checkIsMember($uid, $cid) == TRUE || $this->circle_applicant_model->checkIsApplying($uid, $cid) == TRUE){
					$this->apioutput->apiResponseError('您已经加入或申请加入过该圈，请勿重复提交申请！');
				}
	
				$this->circle_user_model->begin();
				$data = array(
						'circle_id'	=>	$cid,
						'user_id'	=>	$uid
				);
				if($this->circle_user_model->checkIsConcerned($uid, $cid) != TRUE){
					$res = $this->circle_user_model->createEntity($data);
					if($res <= 0){
						$this->apioutput->apiResponseError('申请加入失败，请稍后重试！');
					}
				}
				$res = $this->circle_applicant_model->createEntity($data);
				if(!$res){
					$this->circle_user_model->rollback();
					$this->apioutput->apiResponseError('申请加入失败，请稍后重试！');
				}
	
				$this->circle_user_model->commit();
	
				$this->apioutput->apiResponseSuccess();
				break;
			case 'quit':
				if($this->circle_user_model->checkIsMember($uid, $cid) != TRUE){
					$this->apioutput->apiResponseError('您不是该圈的成员！');
				}
	
				$this->circle_user_model->begin();
				$res = $this->circle_user_model->quitcircle($uid, $cid);
				if(!$res){
					$this->circle_user_model->rollback();
					$this->apioutput->apiResponseError('取消关注失败，请稍后重试！');
				}
				$res = $this->circle_applicant_model->cleardata($uid, $cid);
				if(!$res){
					$this->circle_user_model->rollback();
					$this->apioutput->apiResponseError('取消关注失败，请稍后重试！');
				}
	
				$this->circle_user_model->commit();
	
				$this->apioutput->apiResponseSuccess();
				break;
			default:
				$this->apioutput->apiResponseError('非法请求，请联系管理员！');
		}
	
		if($this->circle_user_model->checkIsMember($uid, $cid) == TRUE){
			$this->msgblock->addError('您已经加入过该圈，请勿重复提交申请！');
			$this->apioutput->apiResponseError('您已经加入过该圈，请勿重复提交申请！');
		}
	
		$this->apioutput->apiResponseSuccess();
	}
}